package com.blog.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.blog.util.StringUtil;
import com.blog.util.WebFileUtil;
import com.blog.util.PageUtil;
import com.blog.entity.Blog;
import com.blog.entity.Comment;
import com.blog.lucene.BlogIndex;
import com.blog.service.background.IBlogService;
import com.blog.service.background.ICommentService;

@Controller
public class IndexController {
	
	private static final Integer PageSize=10;
	@Autowired
	private IBlogService blogService;
	
	@Autowired
	private ICommentService commentService;
	
	@RequestMapping("/")
	public String indexPage() {
		return "redirect:/index";
	}
	
	@RequestMapping("/index")
	public String index(String page,String typeId,String releaseDateStr,HttpServletRequest request,ModelMap modelMap) throws Exception {
		
		if(StringUtil.isEmpty(page)){
			page="1";
		}
		Integer pageNo=Integer.parseInt(page);
		
		HashMap<String,Object> map=new HashMap<String,Object>();
		map.put("typeId", typeId);
		map.put("releaseDateStr", releaseDateStr);
		map = blogService.getBlogListBySearchCondition(map,pageNo,PageSize);
		List<Blog> blogList = (List<Blog>) map.get("blogList"); 
		for(Blog blog:blogList){
			//用于将存放博客内容里面的图片抽出并生成缩略图-用于前端页面展示
			List<String> imagesList=blog.getImagesList();
			
			String blogInfo=blog.getContent();
			Document doc=Jsoup.parse(blogInfo);
			
			//查找扩展名是jpg的图片：根据页面需要拿n张图片,这里拿了3张
			Elements jpgs=doc.select("img[src$=.jpg]"); 
			if (jpgs!=null && jpgs.size()>0) {
				for(int i=0;i<jpgs.size();i++){
					Element jpg=jpgs.get(i);
					imagesList.add(jpg.toString());
					if(i==2){
						break;
					}
				}
			}
		}
		
		modelMap.addAttribute("blogList", blogList);
		//查询参数
		StringBuffer param=new StringBuffer(); 
		if(StringUtil.isNotEmpty(typeId)){
			param.append("typeId="+typeId+"&");
		}
		if(StringUtil.isNotEmpty(releaseDateStr)){
			param.append("releaseDateStr="+releaseDateStr+"&");
		}
		
		Long totalRecord=(Long) map.get("total");
		String genPagination=PageUtil.genPagination(request.getContextPath()+"/index",totalRecord,pageNo,PageSize,param.toString());
		modelMap.addAttribute("pageCode",genPagination);
		modelMap.addAttribute("mainPage", "./blog/list.jsp");
		modelMap.addAttribute("pageTitle","个人博客系统");
		
		blogList = blogService.getAllBlog();
		
		new BlogIndex().createIndexInit(blogList, request);
		
		
		
		return "/forground/index.jsp";
		
	}
	
	@RequestMapping("/articles/{id}")
	public String articles(@PathVariable Integer id,HttpServletRequest request,ModelMap modelMap) {
		Blog blog = blogService.getBlogById(id);
		

		String keyWords=blog.getKeyWord();
		
		if(StringUtil.isNotEmpty(keyWords)){
			String arr[]=keyWords.split(" ");
			modelMap.addAttribute("keyWords",StringUtil.filterWhite(Arrays.asList(arr)));			
		}else{
			modelMap.addAttribute("keyWords",null);			
		}
		modelMap.addAttribute("blog", blog);
		Integer clickHit=blog.getClickHit();
		clickHit = (clickHit==null)?0:clickHit+1;
		//博客点击次数加1
		blog.setClickHit(clickHit); 
		blogService.editSaveBlog(blog);
		
		List<Comment> commentList = commentService.getCommentsByBlogId(id);
		
		modelMap.addAttribute("commentList", commentList); 
		modelMap.addAttribute("pageCode", this.genUpAndDownPageCode(blogService.getPrevBlog(id),blogService.getNextBlog(id),request.getServletContext().getContextPath()));
		modelMap.addAttribute("mainPage", "./blog/view.jsp");
		modelMap.addAttribute("pageTitle",blog.getTitle());
		
		return "/forground/index.jsp";
		
	}
	
	
	
	/**
	 * title:BlogController.java
	 * description: 获取下一篇博客和下一篇博客
	 * time:2018年1月17日 下午10:14:03
	 * author:debug-steadyjack
	 * @param lastBlog
	 * @param nextBlog
	 * @param projectContext
	 * @return String
	 */
	private String genUpAndDownPageCode(Blog lastBlog,Blog nextBlog,String projectContext){
		StringBuffer pageCode=new StringBuffer();
		if(lastBlog==null || lastBlog.getId()==null){
			pageCode.append("<p>上一篇：没有了</p>");
		}else{
			pageCode.append("<p>上一篇：<a href='"+projectContext+"/articles/"+lastBlog.getId()+"'>"+lastBlog.getTitle()+"</a></p>");
		}
		if(nextBlog==null || nextBlog.getId()==null){
			pageCode.append("<p>下一篇：没有了</p>");
		}else{
			pageCode.append("<p>下一篇：<a href='"+projectContext+"/articles/"+nextBlog.getId()+"'>"+nextBlog.getTitle()+"</a></p>");
		}
		return pageCode.toString();
	}
	
	
	
	
	/**
	 * 获取上一页，下一页代码 查询博客用到(简单的分页)
	 * @param page 当前页
	 * @param totalNum 总记录数
	 * @param q 查询关键字
	 * @param pageSize 每页大小
	 * @param projectContext
	 * @return
	 */
	private String genUpAndDownPageCode(Integer page,Integer totalNum,String q,Integer pageSize,String projectContext){
		long totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
		StringBuffer pageCode=new StringBuffer();
		if(totalPage==0){
			return "";
		}else{
			pageCode.append("<nav>");
			pageCode.append("<ul class='pager' >");
			if(page>1){
				pageCode.append("<li><a href='"+projectContext+"/searchByWord?page="+(page-1)+"&queryWord="+q+"'>上一页</a></li>");
			}else{
				pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
			}
			if(page<totalPage){
				pageCode.append("<li><a href='"+projectContext+"/searchByWord?page="+(page+1)+"&queryWord="+q+"'>下一页</a></li>");				
			}else{
				pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");				
			}
			pageCode.append("</ul>");
			pageCode.append("</nav>");
		}
		return pageCode.toString();
	}
	
	
	@RequestMapping("/searchByWord")
	public String searchByWord(String queryWord,String page,HttpServletRequest request,Model model) throws Exception {
		if(queryWord == null) {
			return "redirect:/index";
		}
		
		if(StringUtil.isEmpty(page)){
			page="1";
		}
		
		BlogIndex blogIndex = new BlogIndex();
		
		List<Blog> blogList=blogIndex.searchBlog(queryWord.trim(),request);
		Integer pageNo=Integer.parseInt(page);
		Integer pageSize=10;
		Integer toIndex=blogList.size()>=pageNo*pageSize?pageNo*pageSize:blogList.size();
		
		model.addAttribute("mainPage","./blog/result.jsp");
		
		//list的subList是分页的一种:返回列表中指定的 fromIndex（包括 ）和 toIndex（不包括）之间的部分视图
		model.addAttribute("blogList",blogList.subList((pageNo-1)*pageSize, toIndex));
		model.addAttribute("pageCode",this.genUpAndDownPageCode(pageNo, blogList.size(), queryWord,pageSize,request.getServletContext().getContextPath()));
		model.addAttribute("q",queryWord);
		model.addAttribute("resultTotal",blogList.size());
		model.addAttribute("pageTitle","搜索关键字'"+queryWord+"'结果页面_ssm整合进阶个人博客系统");
		
		return "/forground/index.jsp";
	}
	
	
	
	@RequestMapping("/download")
	public String download(Model model)throws Exception{
		
		model.addAttribute("mainPage", "./common/download.jsp");
		model.addAttribute("pageTitle","本站源码下载页面_Java开源博客系统");
		
		return "/forground/index.jsp";
	}
	
	
	
	
	
	@RequestMapping("/downloadFile")
	public void downloadFile(String fileUrl,String fileName,HttpServletRequest request,HttpServletResponse response) {
		WebFileUtil.downloadFile(request, response, fileUrl, fileName);
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
